package com.fileBrowser.server;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fileBrowser.client.FileManager;
import com.fileBrowser.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {
	
	public FileManager renameSelected(String selectedFile, String parent, String renamed) {
		
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(parent);
		stringBuilder.append("\\");
		stringBuilder.append(renamed);
		
		final String newID = stringBuilder.toString();

		File content = new File(selectedFile);
		content.renameTo(new File(newID));
		
		FileManager fileManager = new FileManager(newID, parent, renamed);
		
		return fileManager;
	}

	public FileManager deleteSelected(String selectedFile) {

		File content = new File(selectedFile);
		FileManager fileManager = new FileManager(content.getAbsolutePath(), content.getParent(),
				content.getName());

		if (content.isDirectory()) {

			File[] files = content.listFiles();

			for (File file : files) {

				if (file.isDirectory()) {
					deleteSelected(file.getAbsolutePath());
				}
				file.delete();
			}
		}
		content.delete();
		
		return fileManager;
	}

	public FileManager getSelected(String selectedFile) {

		File content = new File(selectedFile);
		List<FileManager> children = new ArrayList<FileManager>();
		
		if (content.isDirectory()) {
			File[] fList = content.listFiles();

			for (File file : fList) {

				FileManager child = new FileManager(file.getAbsolutePath(), file.getParent(), file.getName());

				if (file.isDirectory()) {
					child.setIsDir(true);
				} else {
					child.setIsDir(false);
				}

				children.add(child);

			}
		}

		FileManager fileManager = new FileManager(content.getAbsolutePath(), content.getParent(),
				content.getName());
		fileManager.setChildren(children);

		return fileManager;
	}
}
